<template>
    <div class="carousel-manage">
        <div class="manage-header">
            <h2>轮播图管理</h2>
            <el-button type="primary" @click="openAddDialog" class="add-button">
                <el-icon>
                    <plus />
                </el-icon> 新增轮播图
            </el-button>
        </div>

        <!-- 数据表格 -->
        <el-table :data="carouselList" border v-loading="loading" style="width: 100%;" class="carousel-table">
            <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
            <el-table-column prop="title" label="标题" width="180"></el-table-column>
            <el-table-column label="图片" width="200" align="center">
                <template #default="scope">
                    <el-image style="width: 180px; height: 90px;" :src="scope.row.imageUrl" fit="cover"
                        :preview-src-list="[scope.row.imageUrl]" class="carousel-preview-image">
                        <template #error>
                            <div class="image-error">
                                <el-icon><picture-filled /></el-icon>
                                <span>加载失败</span>
                            </div>
                        </template>
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column prop="videoTitle" label="关联视频" width="180"></el-table-column>
            <el-table-column prop="url" label="跳转链接" show-overflow-tooltip></el-table-column>
            <el-table-column prop="orderNum" label="排序" width="80" align="center"></el-table-column>
            <el-table-column label="状态" width="100" align="center">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'info'" effect="dark">
                        {{ scope.row.status === 1 ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right" align="center">
                <template #default="scope">
                    <div class="table-actions">
                        <el-tooltip content="编辑" placement="top">
                            <el-button size="small" type="primary" @click="handleEdit(scope.row)" circle>
                                <el-icon>
                                    <edit />
                                </el-icon>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button size="small" type="danger" @click="handleDelete(scope.row)" circle>
                                <el-icon>
                                    <delete />
                                </el-icon>
                            </el-button>
                        </el-tooltip>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 空数据展示 -->
        <el-empty v-if="carouselList.length === 0 && !loading" description="暂无轮播图数据" class="empty-data">
            <el-button type="primary" @click="openAddDialog">
                <el-icon>
                    <plus />
                </el-icon> 添加轮播图
            </el-button>
        </el-empty>

        <!-- 分页组件 -->
        <el-pagination v-if="carouselList.length > 0" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" :current-page="pagination.currentPage" :page-sizes="[5, 10, 20, 30]"
            :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
            background class="pagination">
        </el-pagination>

        <!-- 新增/编辑对话框 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" @closed="resetForm" destroy-on-close
            class="carousel-dialog" :close-on-click-modal="false">
            <div class="dialog-content">
                <el-form :model="carouselForm" :rules="rules" ref="carouselForm" label-width="100px"
                    class="carousel-form">
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="carouselForm.title" placeholder="请输入轮播图标题" maxlength="50"
                            show-word-limit></el-input>
                    </el-form-item>

                    <el-form-item label="图片" prop="imageUrl">
                        <el-upload class="carousel-uploader" action="/api/upload/image" :show-file-list="false"
                            :on-success="handleImageSuccess" :before-upload="beforeImageUpload" :headers="uploadHeaders"
                            drag>
                            <div class="upload-area" :class="{ 'has-image': carouselForm.imageUrl }">
                                <img v-if="carouselForm.imageUrl" :src="carouselForm.imageUrl" class="carousel-image">
                                <template v-else>
                                    <el-icon class="upload-icon"><upload-filled /></el-icon>
                                    <div class="upload-text">拖拽文件或点击上传轮播图</div>
                                    <div class="upload-hint">建议尺寸: 1920 × 500 像素</div>
                                </template>
                            </div>
                        </el-upload>
                    </el-form-item>

                    <el-form-item label="关联视频" prop="vid">
                        <div class="video-search-container">
                            <el-autocomplete v-model="videoSearchInput" :fetch-suggestions="queryVideos"
                                placeholder="请输入视频标题搜索" @select="handleVideoSelect" :trigger-on-focus="false"
                                class="video-search" clearable>
                                <template #default="{ item }">
                                    <div class="video-item">
                                        <img class="video-cover" :src="item.coverUrl" alt="视频封面">
                                        <div class="video-info">
                                            <div class="video-title">{{ item.title }}</div>
                                            <div class="video-uploader">UP主: {{ item.username }}</div>
                                        </div>
                                    </div>
                                </template>
                            </el-autocomplete>

                            <div v-if="selectedVideo.vid" class="selected-video-info">
                                <el-tag closable type="success" @close="removeSelectedVideo">
                                    <el-icon><video-camera /></el-icon>
                                    已选择: {{ selectedVideo.title }}
                                </el-tag>
                            </div>
                        </div>
                    </el-form-item>

                    <el-form-item label="自定义链接" prop="url">
                        <el-input v-model="carouselForm.url" placeholder="可选: 自定义跳转链接，优先级高于关联视频">
                            <template #prepend>
                                <el-icon>
                                    <link />
                                </el-icon>
                            </template>
                        </el-input>
                    </el-form-item>

                    <el-form-item label="排序" prop="orderNum">
                        <el-input-number v-model="carouselForm.orderNum" :min="1" :max="99"
                            controls-position="right"></el-input-number>
                        <span class="form-tip">数值越小越靠前</span>
                    </el-form-item>

                    <el-form-item label="状态" prop="status">
                        <el-switch v-model="carouselForm.status" :active-value="1" :inactive-value="0" active-text="启用"
                            inactive-text="禁用" inline-prompt class="status-switch">
                        </el-switch>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false" plain>取 消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="submitting" :disabled="submitting">
                        {{ submitting ? '提交中...' : '确 定' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: "CarouselManage",
    data() {
        return {
            loading: true,
            submitting: false, // 提交表单的加载状态
            carouselList: [],
            pagination: {
                currentPage: 1,
                pageSize: 10,
                total: 0
            },
            dialogVisible: false,
            dialogTitle: "新增轮播图",
            carouselForm: {
                id: null,
                title: "",
                imageUrl: "",
                vid: null,
                url: "",
                orderNum: 1,
                status: 1
            },
            rules: {
                title: [
                    { required: true, message: "请输入轮播图标题", trigger: "blur" },
                    { max: 50, message: "长度不能超过50个字符", trigger: "blur" }
                ],
                imageUrl: [
                    { required: true, message: "请上传轮播图", trigger: "change" }
                ],
                orderNum: [
                    { required: true, message: "请设置排序", trigger: "blur" }
                ]
            },
            videoSearchInput: "",
            selectedVideo: {},
            uploadHeaders: {
                Authorization: `Bearer ${localStorage.getItem('teri_token') || ''}`
            }
        };
    },
    mounted() {
        this.getCarouselList();
    },
    methods: {
        // 获取轮播图列表
        async getCarouselList() {
            this.loading = true;
            try {
                const res = await this.$get("/admin/carousel/list", {
                    params: {
                        page: this.pagination.currentPage,
                        pageSize: this.pagination.pageSize
                    }
                });

                if (res.data.code === 200) {
                    this.carouselList = res.data.data.records || [];
                    this.pagination.total = res.data.data.total || 0;

                    // 确保数据完整性
                    this.carouselList = this.carouselList.map(item => {
                        return {
                            ...item,
                            imageUrl: item.imageUrl || '',
                            videoTitle: item.videoTitle || '暂无关联视频',
                            orderNum: item.orderNum || 1,
                            status: item.status || 0
                        };
                    });
                } else {
                    this.$message.error(res.data.message || "获取轮播图列表失败");
                }
            } catch (error) {
                console.error("获取轮播图列表错误:", error);
                this.$message.error("网络错误，获取轮播图列表失败");
            } finally {
                this.loading = false;
            }
        },

        // 打开新增对话框
        openAddDialog() {
            this.dialogTitle = "新增轮播图";
            this.resetForm();
            this.dialogVisible = true;
        },

        // 处理编辑
        async handleEdit(row) {
            this.dialogTitle = "编辑轮播图";
            this.resetForm();
            try {
                const res = await this.$get(`/admin/carousel/${row.id}`);
                if (res.data.code === 200) {
                    const data = res.data.data;
                    this.carouselForm = {
                        id: data.id,
                        title: data.title || '',
                        imageUrl: data.imageUrl || '',
                        vid: data.vid || null,
                        url: data.url || "",
                        orderNum: data.orderNum || 1,
                        status: data.status || 0
                    };
                    if (data.vid && data.videoTitle) {
                        this.selectedVideo = {
                            vid: data.vid,
                            title: data.videoTitle || '未知视频',
                            coverUrl: data.videoCoverUrl || '',
                            username: data.videoUsername || '未知用户'
                        };
                    }
                    this.dialogVisible = true;
                } else {
                    this.$message.error(res.data.message || "获取轮播图详情失败");
                }
            } catch (error) {
                console.error("获取轮播图详情错误:", error);
                this.$message.error("网络错误，获取轮播图详情失败");
            }
        },

        // 处理删除
        handleDelete(row) {
            this.$confirm("确认删除该轮播图?", "提示", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "warning"
            }).then(async () => {
                try {
                    const res = await this.$axios({
                        method: 'delete',
                        url: `/api/admin/carousel/${row.id}`,
                        headers: {
                            'Authorization': `Bearer ${localStorage.getItem('teri_token') || ''}`
                        }
                    });

                    if (res.data.code === 200) {
                        this.$message.success("删除成功");
                        this.getCarouselList();
                    } else {
                        this.$message.error(res.data.message || "删除失败");
                    }
                } catch (error) {
                    console.error("删除轮播图错误:", error);
                    this.$message.error("网络错误，删除失败");
                }
            }).catch(() => { });
        },

        // 图片上传成功回调
        handleImageSuccess(res) {
            if (res.code === 200) {
                this.carouselForm.imageUrl = res.data;
                this.$refs.carouselForm.validateField('imageUrl');
            } else {
                this.$message.error(res.message || "图片上传失败");
            }
        },

        // 图片上传前的验证
        beforeImageUpload(file) {
            const isJPG = file.type === "image/jpeg";
            const isPNG = file.type === "image/png";
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG && !isPNG) {
                this.$message.error("上传图片只能是 JPG 或 PNG 格式!");
                return false;
            }
            if (!isLt2M) {
                this.$message.error("上传图片大小不能超过 2MB!");
                return false;
            }
            return true;
        },

        // 查询视频列表
        async queryVideos(queryString, callback) {
            if (queryString.length < 2) {
                callback([]);
                return;
            }

            try {
                const res = await this.$get("/admin/video/search", {
                    params: { keyword: queryString }
                });
                if (res.data.code === 200 && Array.isArray(res.data.data)) {
                    callback(res.data.data || []);
                } else {
                    callback([]);
                }
            } catch (error) {
                console.error("搜索视频错误:", error);
                callback([]);
            }
        },

        // 选择视频
        handleVideoSelect(item) {
            this.selectedVideo = item;
            this.carouselForm.vid = item.vid;
            this.videoSearchInput = "";
        },

        // 移除选择的视频
        removeSelectedVideo() {
            this.selectedVideo = {};
            this.carouselForm.vid = null;
        },

        // 提交表单
        submitForm() {
            this.$refs.carouselForm.validate(async valid => {
                if (valid) {
                    this.submitting = true;
                    const isEdit = this.carouselForm.id !== null;
                    const method = isEdit ? "put" : "post";
                    const url = isEdit ? `/admin/carousel/${this.carouselForm.id}` : "/admin/carousel";

                    // 确保传递所有必要字段
                    const formData = {
                        ...this.carouselForm,
                        videoTitle: this.selectedVideo.title || '',
                        videoUsername: this.selectedVideo.username || '',
                        videoCoverUrl: this.selectedVideo.coverUrl || ''
                    };

                    try {
                        const res = await this.$axios({
                            method: method,
                            url: `/api${url}`,
                            data: formData,
                            headers: {
                                'Content-Type': 'application/json',
                                'Authorization': `Bearer ${localStorage.getItem('teri_token') || ''}`
                            }
                        });

                        if (res.data.code === 200) {
                            this.$message.success(isEdit ? "更新成功" : "添加成功");
                            this.dialogVisible = false;
                            this.getCarouselList();
                        } else {
                            this.$message.error(res.data.message || (isEdit ? "更新失败" : "添加失败"));
                        }
                    } catch (error) {
                        console.error(isEdit ? "更新错误:" : "添加错误:", error);
                        this.$message.error(isEdit ? "更新失败" : "添加失败");
                    } finally {
                        this.submitting = false;
                    }
                }
            });
        },

        // 重置表单
        resetForm() {
            if (this.$refs.carouselForm) {
                this.$refs.carouselForm.resetFields();
            }
            this.carouselForm = {
                id: null,
                title: "",
                imageUrl: "",
                vid: null,
                url: "",
                orderNum: 1,
                status: 1
            };
            this.selectedVideo = {};
            this.videoSearchInput = "";
        },

        // 处理分页大小变化
        handleSizeChange(size) {
            this.pagination.pageSize = size;
            this.pagination.currentPage = 1;
            this.getCarouselList();
        },

        // 处理页码变化
        handleCurrentChange(page) {
            this.pagination.currentPage = page;
            this.getCarouselList();
        }
    }
}
</script>

<style scoped>
.carousel-manage {
    padding: 30px;
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
    min-height: calc(100vh - 120px);
    margin: 20px;
}

.manage-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;
}

.manage-header h2 {
    font-size: 22px;
    font-weight: 600;
    color: #333;
    margin: 0;
    position: relative;
    padding-left: 14px;
}

.manage-header h2::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 22px;
    background-color: #409EFF;
    border-radius: 2px;
}

.add-button {
    padding: 9px 16px;
    font-weight: 500;
}

/* 表格样式 */
.carousel-table {
    border-radius: 8px;
    overflow: hidden;
    margin-bottom: 20px;
    border: 1px solid #ebeef5;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.03);
}

/* 图片预览样式 */
.carousel-preview-image {
    border-radius: 6px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
}

.carousel-preview-image:hover {
    transform: scale(1.02);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.image-error {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 90px;
    color: #909399;
}

/* 表格操作按钮样式 */
.table-actions {
    display: flex;
    justify-content: center;
    gap: 12px;
}

/* 分页样式 */
.pagination {
    margin-top: 24px;
    text-align: right;
    padding: 12px 0;
}

/* 空数据样式 */
.empty-data {
    margin: 80px auto;
    text-align: center;
}

/* 对话框样式 */
:deep(.carousel-dialog) {
    border-radius: 8px;
    overflow: hidden;
}

:deep(.carousel-dialog .el-dialog__header) {
    padding: 20px 24px;
    margin-bottom: 0;
    position: relative;
    border-bottom: 1px solid #f0f0f0;
}

:deep(.carousel-dialog .el-dialog__title) {
    font-size: 18px;
    font-weight: 600;
    color: #333;
}

:deep(.carousel-dialog .el-dialog__headerbtn) {
    top: 20px;
}

:deep(.carousel-dialog .el-dialog__body) {
    padding: 24px;
}

:deep(.carousel-dialog .el-dialog__footer) {
    padding: 16px 24px;
    border-top: 1px solid #f0f0f0;
    display: flex;
    justify-content: center;
}

.dialog-content {
    max-height: 60vh;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 5px;
}

/* 滚动条样式 */
.dialog-content::-webkit-scrollbar {
    width: 6px;
}

.dialog-content::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 3px;
}

.dialog-content::-webkit-scrollbar-track {
    background-color: #f5f5f5;
    border-radius: 3px;
}

.carousel-form {
    width: 100%;
}

/* 上传组件样式 */
.carousel-uploader {
    width: 100%;
}

.carousel-uploader :deep(.el-upload) {
    width: 100%;
    cursor: pointer;
}

.upload-area {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 180px;
    border: 2px dashed #e0e0e0;
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.3s;
    background-color: #fafafa;
}

.upload-area:hover {
    border-color: #409EFF;
    background-color: #f5f7fa;
}

.upload-area.has-image {
    background-color: transparent;
    border-color: #90caf9;
}

.upload-icon {
    font-size: 36px;
    color: #a0a0a0;
    margin-bottom: 12px;
}

.upload-text {
    font-size: 15px;
    color: #606266;
    margin-bottom: 4px;
}

.upload-hint {
    font-size: 13px;
    color: #909399;
}

.carousel-image {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

/* 表单项样式 */
:deep(.el-form-item) {
    margin-bottom: 22px;
}

:deep(.el-form-item__label) {
    font-weight: 500;
}

.form-tip {
    color: #909399;
    font-size: 13px;
    margin-left: 10px;
}

/* 视频搜索与展示样式 */
.video-search-container {
    width: 100%;
}

.video-search {
    width: 100%;
}

.video-item {
    display: flex;
    align-items: center;
    padding: 10px 0;
}

.video-cover {
    width: 80px;
    height: 45px;
    margin-right: 12px;
    object-fit: cover;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.video-info {
    flex: 1;
}

.video-title {
    font-size: 14px;
    font-weight: 500;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-bottom: 5px;
}

.video-uploader {
    font-size: 12px;
    color: #909399;
}

.selected-video-info {
    margin-top: 12px;
}

.selected-video-info .el-tag {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 0 10px;
    height: 32px;
}

/* 按钮样式 */
.dialog-footer {
    display: flex;
    justify-content: center;
    gap: 16px;
}

.dialog-footer .el-button {
    padding: 10px 24px;
    min-width: 100px;
    font-size: 14px;
    font-weight: 500;
}

.status-switch {
    width: 90px;
}
</style>